import { connect } from 'umi';
import { Form, Spin, message } from 'antd';
import { useEffect, useState } from 'react';
import '../common/style.less';
import { detailAssetApplyUesServices, syncPDFtoOAServicesUse } from '../services/DetailOAUseService';
import { ChangeControllerContext } from '../common/useOAUseContext';
import { useOAReducer, IUseOAActionEnum } from '../common/useOAUseReducer';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { getInvoiceCode, getPersonalInfo, getPosIDs, getTenantID, getUserID, renderWaterMarkDom } from '@/utils';
import { RevokeModal } from '../../../Acomponents/RevokeModal';
import { ILoadMapTypeAll } from '@/common';
import { SHTG_CHECKSTATE, SHZ_CHECKSTATE, setOAMessageSev } from '../../../Acommon';
import { approvedAssetApplyUseSerivice, dealNumAssetApplyUseSerivice, editAssetApplyUesSerivice } from '../services';
import { OpenAssetModal } from './OpenAssetModal';
import { OpenMaterialModal } from './OpenMaterialModal';
import { LYflowBusinessType } from '../common/FormatUse';

/** 领用OA办理页面 */
const DetailInfoViewOA: React.FC<Record<string, any>> = ({ locationProps, curRes }) => {
  /** 样式根名称 */
  const prefix = 'experts-manage-oa-';

  /** 引入上下文 */
  const { assetList, materialList, assetForm, isEdit, selectUserInfo, useOADispatch } = useOAReducer();

  /** 保存详情 */
  const [infoObj, setInfoObj] = useState<Record<string, any>>({});

  /** 撤销弹窗 */
  const [invalidState, setInvalidState] = useState<Record<string, any>>({});

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});

  /** 打开选择资产列表 */
  const [openAssetModal, setOpenAssetModal] = useState<boolean>(false);

  /** 打开选择材料列表 */
  const [openMaterialModal, setOpenMaterialModal] = useState<boolean>(false);

  /** 审批完成 */
  const [finish, setFinish] = useState<boolean>(false);

  /** 选中的项的materialId */
  const [editAssetId, setEditAssetId] = useState<any>({});

  // 选中的项的materialId
  const changeEditAssetId = (id: string, index: number, text: any) => {
    let obj: any = {
      id,
      index: index,
      text,
    };
    setEditAssetId(obj);
  };

  // 打开选择资产列表方法
  const openAssetModalFun = () => {
    setOpenAssetModal(true);
  };
  // 打开选择材料列表方法
  const openMaterialModalFun = () => {
    setOpenMaterialModal(true);
  };

  /** 获取详情 */
  const { detailAssetApplyUesRun, detailAssetApplyUesLoading, detailAssetApplyUesReload } = detailAssetApplyUesServices((res) => {
    if (res?.msgFlag) {
      setInfoObj(res?.obj);

      useOADispatch({
        type: IUseOAActionEnum.SELECT_ASSET,
        payload: res?.obj?.applyNumberAssetList,
      });
      useOADispatch({
        type: IUseOAActionEnum.SELECT_MATERIAL,
        payload: res?.obj?.applyNumberMaterialList,
      });

      // 做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`]) {
        let workFlowNode = infoObject?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          setOAMessageRun({
            // 已读未办
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }
    }
  });

  /** 领用-最后一个人审核通过后调用的同步接口 */
  const { approvedAssetApplyUseRun, approvedAssetApplyUseLoading } = approvedAssetApplyUseSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  });

  /** 审核中，审核通过/作废 开关 */
  const [isSHTGFlag, setIsSHTGFlag] = useState(false);

  /** 同步审核记录给档案 */
  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServicesUse((res) => {});
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList =
      infoObj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1011`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /** 编辑领用 */
  const { editAssetApplyUesRun, editAssetApplyUesLoading } = editAssetApplyUesSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      detailAssetApplyUesRun({ id: res?.obj?.id });
    } else {
      message.error(res?.msg);
    }
  });

  /** 暂存按钮  保存数据 */
  const handleSave = (assetData: Record<string, any>) => {
    // 校验选中的材料或资产
    if (assetData?.length === 0 && materialList?.length === 0) {
      message.error('请选择资产或材料!');
      return;
    }
    if (infoObj?.applyType == 0 && (assetData?.length === 0 || materialList?.length === 0)) {
      message.error('请选择资产或材料!');
      return;
    }
    const params = {
      ...infoObj,
      applyNumberAssetList: infoObj?.applyType != 2 ? assetData : [], // 资产信息列表
      applyNumberMaterialList: infoObj?.applyType != 1 ? materialList : [], // 材料信息列表
    };
    // 修改接口
    editAssetApplyUesRun(params);
  };

  /** 监听审核状态-复核通过后可以编辑 */
  useEffect(() => {
    /** 处理流程办理数据 */
    const taskType: string = LYflowBusinessType();
    const taskHandInfo: Record<string, any> = infoObj?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.taskName == '财务资产部专责复核' &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID() &&
      infoObj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`
    ) {
      useOADispatch({
        type: IUseOAActionEnum.EDIT_STATUS,
        payload: true,
      });
    } else {
      useOADispatch({
        type: IUseOAActionEnum.EDIT_STATUS,
        payload: false,
      });
    }
  }, [infoObj?.checkState]);

  /** 监听数据状态改变，更改状态 */
  useEffect(() => {
    if (
      infoObj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
      infoObj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1003`
    ) {
      setFinish(true);
    } else {
      setFinish(false);
    }
    if (
      (infoObj?.state && infoObj?.state == `${getTenantID()}${ILoadMapTypeAll.STORAGE_USE_STATUS}1001` && infoObj?.checkState == SHZ_CHECKSTATE()) ||
      (infoObj?.state && infoObj?.checkState == `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1006`)
    ) {
      setIsSHTGFlag(true);
    }
    if (isSHTGFlag && infoObj?.checkState == SHTG_CHECKSTATE()) {
      approvedAssetApplyUseRun({ ...infoObj, workflowResult: true });
      syncPDFtoOARunfun(infoObj);
    }
  }, [infoObj?.state, infoObj?.checkState]);

  /** 撤销释放物料 */
  const { dealNumAssetApplyUseRun, dealNumAssetApplyUseLoading } = dealNumAssetApplyUseSerivice(() => {});

  /** 撤销回调函数 */
  const revokeReloadCallback = async () => {
    await dealNumAssetApplyUseRun({ ...infoObj, dealType: 'back' });
    detailAssetApplyUesReload();
  };
  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.id) {
      detailAssetApplyUesRun({ id: locationProps?.state?.id });
    }
  }, [locationProps?.state?.id]);

  // 初始化水印
  // useEffect(() => {
  //   renderWaterMarkDom('bidEvalOAPage-divBox', true);
  //   return () => {
  //     renderWaterMarkDom('bidEvalOAPage-divBox', false);
  //   };
  // }, []);

  return (
    <ChangeControllerContext.Provider
      value={{
        styleFixCls: prefix,
        infoObj,
        reloadDetail: detailAssetApplyUesReload,
        invalidState,
        setInvalidState,
        curRes,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
        useOADispatch,
        assetForm,
        assetList,
        materialList,
        isEdit,
        selectUserInfo,
      }}
    >
      <Spin
        spinning={
          detailAssetApplyUesLoading ||
          setOAMessageLoaidng ||
          syncPDFtoOALoading ||
          dealNumAssetApplyUseLoading ||
          approvedAssetApplyUseLoading ||
          editAssetApplyUesLoading
        }
      >
        <div className={`${prefix}infoViewOA`} id={'bidEvalOAPage-divBox'}>
          <DetailInfoTopViewOA locationProps={locationProps} />
          <DetailInfoCenterViewOA
            finish={finish}
            openAssetModalFun={openAssetModalFun}
            openMaterialModalFun={openMaterialModalFun}
            changeEditAssetId={changeEditAssetId}
            pageTypeOA={locationProps?.state?.pageType}
          />
          <DetailInfoBottomViewOA locationProps={locationProps} />
        </div>

        {/* 选择资产列表弹窗组件 */}
        {openAssetModal && (
          <OpenAssetModal
            curRes={curRes}
            isShowModal={openAssetModal}
            editState={isEdit}
            editAssetId={editAssetId}
            handleEditSave={handleSave}
            onClose={() => {
              setOpenAssetModal(false);
            }}
            queryType={'1'}
          />
        )}
        {/* 选择材料列表弹窗组件 */}
        {openMaterialModal && (
          <OpenMaterialModal
            curRes={curRes}
            isShowModal={openMaterialModal}
            queryType={'1'}
            onClose={() => {
              setOpenMaterialModal(false);
            }}
          />
        )}
      </Spin>

      {invalidState?.isShow && (
        <RevokeModal
          resObj={invalidState?.resObj}
          revokeRequestUrl={'/assetApplyUes/revoke'}
          onClose={() => setInvalidState({})}
          reqBody={{ state: `${getTenantID()}${ILoadMapTypeAll?.STORAGE_USE_STATUS}1000` }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.ownerName}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={revokeReloadCallback}
        />
      )}
    </ChangeControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
